package com.maoye.ossp.sys.base.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hotent.base.api.query.QueryFilter;
import com.maoye.ossp.common.entity.Page;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.base.entity.SysBaseCountry;
import com.maoye.ossp.sys.base.entity.SysBaseRegion;
import com.maoye.ossp.sys.base.service.SysBaseCountryService;
import com.maoye.ossp.sys.base.service.SysBaseRegionService;
/**
 * 区域controller类
 * @author liangtao
 * @date   2014-4-17
 */
@Controller
@RequestMapping(value = "sys/base/region/")
public class SysBaseRegionController extends BaseController {
	@Resource
	private SysBaseRegionService sysBaseRegionService ;
	
	@Resource
	private SysBaseCountryService sysBaseCountryService;
	
	/**
	 * 获得区域列表
	 * @param request
	 * @param responser
	 * @throws IOException
	 */
	
	@RequestMapping(value = "getRegionList")
	public String getRegionList(HttpServletRequest request, HttpServletResponse response,Model model,SysBaseRegion region) {
		QueryFilter queryFilter = getQuerFilter(request,region);
		Page<SysBaseRegion> page = (Page<SysBaseRegion>)sysBaseRegionService
				.find(queryFilter);
		Map map=new HashMap();
		List<SysBaseRegion> list =page.getList();
		for(int i=0;i<list.size();i++){
			if(list.get(i).getParent()!=null&&!list.get(i).getParent().equals("")){
			   map.put("id",list.get(i).getParent());
			   list.get(i).setParentArea(sysBaseRegionService.getParentRegionById(map).getName());
			}else{
			list.get(i).setParentArea("无");
			}
			if(sysBaseRegionService.checkIsParent(list.get(i).getCode())){
				//父节点
				list.get(i).setFlag("0"); 
			}else{
				//叶子节点
				list.get(i).setFlag("1"); 
			}
		} 
		page.setList(list);
		model.addAttribute("page", page);
		model.addAttribute("sysBaseRegion",region);
		return resultPage("/sys/base/region/getRegionList", model, request);
	}
	
	/**
	 * 加载区域根节点
	 * @param request
	 * @param responser
	 * @throws IOException
	 */
	@RequestMapping(value ="getzNodes")
	public void getzNodes(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("utf-8");
		String contextPath=request.getContextPath();
		PrintWriter out = response.getWriter();
		StringBuffer json = new StringBuffer();
		Map map = new HashMap();
		List<SysBaseRegion>Regions = sysBaseRegionService.getRootRegion(map);
			json.append("[");
			for(int i = 0; i < Regions.size(); i++){
				SysBaseRegion Region = Regions.get(i);
				Long pid = null;
					//pid = 0L;				
					json.append("{").append("id:").append(Region.getCode()).append(",");
					json.append("pId:").append(Region.getParent()).append(",");
					json.append("name:\"").append(Region.getName()).append("\"").append(",");
					if(sysBaseRegionService.checkIsParent(Region.getCode())){
						json.append("isParent:").append(1);  
					}else{
						json.append("isParent:").append(0);
					}
					json.append(",");
					json.append("open:").append("false"); 
					json.append("}");
					if(i < Regions.size()-1){
						json.append(",");
					}
			}
		json.append("]");
		out.print(json.toString());
		out.flush();
		out.close();		
	}
	
	
	/**
	 * 根据父节点加载子节点
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "regionChild")
	public void ChildlistByPId(HttpServletRequest request, HttpServletResponse response ) throws IOException {	
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String contextPath=request.getContextPath();
		String pId=request.getParameter("treeNodeId");
		StringBuilder json = new StringBuilder();
		Map map = new HashMap();
		map.put("pid", pId);
		List<SysBaseRegion>Regions = sysBaseRegionService.ChildlistByPId(map);
		json.append("[");
		for(int i = 0;i<Regions.size();i++){
			SysBaseRegion Region = Regions.get(i);
			json.append("{").append("id:").append(Region.getCode()).append(",");
			json.append("pId:").append(pId).append(",");
			json.append("name:\"").append(Region.getName()).append("\"").append(",");
			if(sysBaseRegionService.checkIsParent(Region.getCode())){
				json.append("isParent:").append(1);  
			}else{
				json.append("isParent:").append(0);
			}
			json.append(",");
			json.append("open:").append("true"); 
			json.append("}");
			if(i < Regions.size()-1){
				json.append(",");
			}		
		}
		json.append("]");
		out.print(json.toString());
		out.flush();
		out.close();
	}
	
	/**
	 * 增加区域信息
	 * @param region
	 * @param model
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value = "addRegion")
	public String addRegion(HttpServletRequest request,Model model) throws IOException {
		Map map = new HashMap();
		SysBaseRegion sysBaseRegion=new SysBaseRegion();
		model.addAttribute("sysBaseRegion",sysBaseRegion);
		return "/sys/base/region/add";

	}	
	
	
	
	/**
	 * 验证区域编码
	 * @param region
	 * @param model
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value = "checkRegionCode")
	public void checkRegionCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
		Map map = new HashMap();
		String code = request.getParameter("code");	
		map.put("code",code);
		PrintWriter out = response.getWriter();
		JSONObject json = new JSONObject();
		if(sysBaseRegionService.checkRegionCode(map)){
			json.put("resCode",0); //区域号可用
		}else{
			json.put("resCode",1);//区域号不可以用
		}
		out.print(json.toString());
		out.flush();
		out.close();
	}
	
	/**
	 * 保存区域信息
	 * @param region
	 * @param model
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value = "saveRegion")
	public String saveRegion(SysBaseRegion region,HttpServletRequest request,HttpServletResponse response,RedirectAttributes redirectAttributes) throws IOException{
		region.setId(idGenerator.getUId());
		region.setCode(region.getCode().replaceAll(",","").toString());
		region.setParent(region.getParent().replaceAll(",","").toString());
		//设置创建人
		region.setCreatBy("");
		sysBaseRegionService.saveRegion(region);
		addMessage(redirectAttributes, "保存成功");
		return "redirect:getRegionList";
	}
	
	
	/**
	 * 查看区域信息
	 * @param region
	 * @param model
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value ="viewRegion")
	public String viewRegion(HttpServletRequest request, HttpServletResponse response,Model model){
		String code =request.getParameter("code");
		String parentArea =request.getParameter("parentArea");
		Map map = new HashMap();
		map.put("id",code);
		SysBaseRegion sysBaseRegion=null;
		sysBaseRegion=sysBaseRegionService.getParentRegionById(map);
		SysBaseCountry sysBaseCountry=new SysBaseCountry();
		map.put("code",sysBaseRegion.getCountryCode());
		sysBaseCountry=sysBaseCountryService.getCountrybyCode(map);
		model.addAttribute("sysBaseRegion",sysBaseRegion);
		model.addAttribute("parentArea",parentArea);
		if(sysBaseCountry!=null){
			model.addAttribute("countryName",sysBaseCountry.getName());
		}
		return "/sys/base/region/view";
	}
	
	/**
	 * 删除区域信息
	 * @param region
	 * @param model
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value ="removeRegion")
	public String removeRegion(HttpServletRequest request, HttpServletResponse response,RedirectAttributes redirectAttributes){
		Map map = new HashMap();
		String code = request.getParameter("code");
		map.put("code", code);
		sysBaseRegionService.removeRegion(map);
		addMessage(redirectAttributes, "删除成功");
		return "redirect:getRegionList";
	} 
	/**
	 * 更新区域信息
	 * @param region
	 * @param model
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value ="updateRegion")
	public String updateRegion(HttpServletRequest request, HttpServletResponse response,Model model){
		String code =request.getParameter("code");
		String parentArea =request.getParameter("parentArea");
		Map map = new HashMap();
		map.put("id",code);
		SysBaseRegion sysBaseRegion=null;
		sysBaseRegion=sysBaseRegionService.getParentRegionById(map);
		SysBaseCountry sysBaseCountry=new SysBaseCountry();
		map.put("code",sysBaseRegion.getCountryCode());
		sysBaseCountry=sysBaseCountryService.getCountrybyCode(map);
		model.addAttribute("sysBaseRegion",sysBaseRegion);
		model.addAttribute("parentArea",parentArea);
		if(sysBaseCountry!=null){
			model.addAttribute("countryName",sysBaseCountry.getName());
		}
		return "/sys/base/region/update";
	}
	@RequestMapping(value ="saveUpdateRegion")
    public String saveUpdateRegion(SysBaseRegion region,HttpServletRequest request,HttpServletResponse response,RedirectAttributes redirectAttributes){
        //设置修改人
		region.setCode(region.getCode().replaceAll(",","").toString());
		region.setParent(region.getParent().replaceAll(",","").toString());
		region.setUpdateBy("");
		sysBaseRegionService.savaUpdateRegion(region);
		addMessage(redirectAttributes, "修改成功");
		return "redirect:getRegionList";
    }
}
